package com.chentu.mika.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chentu.mika.model.entity.Comment;
import com.chentu.mika.model.result.Result;
import com.chentu.mika.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class CommentController {
    @Autowired
    CommentService commentService;

    @PostMapping("/comments")
    public Result add(@RequestBody Map map) {
        Comment comment = new Comment();
        comment.setContent((String)map.get("content"));
        comment.setProductID((Integer) map.get("productID"));
        comment.setUserID((Integer) map.get("userID"));
        comment.setAudit(0);
        commentService.save(comment);
        return Result.success(null);
    }

    @GetMapping("/comments/{productID}")
    public Result list(@PathVariable("productID") Integer productID) {
        List<Comment> comments = new ArrayList<>();
        for (Comment comment : commentService.list()) {
            if (comment.getProductID().equals(productID)) {
                comments.add(comment);
            }
        }
        return Result.success(comments);
    }

    @DeleteMapping("/comments/{commentID}")
    public Result del (@PathVariable("commentID") String commentID) {
        commentService.remove(Wrappers.<Comment>lambdaQuery().eq(Comment::getCommentID, new BigInteger(commentID).intValue()));
        return Result.success(null);
    }

    @PutMapping("/comments/{commentID}")
    public Result update(@PathVariable("commentID") String commentID, @RequestBody Map map) {
        System.out.println(new BigInteger(commentID).intValue());
        commentService.update(Wrappers.<Comment>lambdaUpdate()
                .eq(Comment::getCommentID, new BigInteger(commentID).intValue())
                .set(Comment::getAudit, map.get("audit")));

        return Result.success(null);
    }
}
